package com.sanyue.codingsettlement.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sanyue.codingsettlement.annotation.AuthCheck;
import com.sanyue.codingsettlement.common.BaseResponse;
import com.sanyue.codingsettlement.common.DeleteRequest;
import com.sanyue.codingsettlement.common.ErrorCode;
import com.sanyue.codingsettlement.common.ResultUtils;
import com.sanyue.codingsettlement.constant.UserConstant;
import com.sanyue.codingsettlement.exception.BusinessException;
import com.sanyue.codingsettlement.exception.ThrowUtils;
import com.sanyue.codingsettlement.manager.AiManager;
import com.sanyue.codingsettlement.model.dto.chart.ChartAddRequest;
import com.sanyue.codingsettlement.model.dto.chart.ChartQueryRequest;
import com.sanyue.codingsettlement.model.dto.chart.GenChartByAiRequest;
import com.sanyue.codingsettlement.model.entity.Chart;
import com.sanyue.codingsettlement.model.entity.User;
import com.sanyue.codingsettlement.model.vo.BiResponse;
import com.sanyue.codingsettlement.model.vo.ChartVO;
import com.sanyue.codingsettlement.service.ChartService;
import com.sanyue.codingsettlement.service.UserService;
import com.sanyue.codingsettlement.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 图表接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;


    @Resource
    private AiManager aiManager;



    // region 增删改查

    /**
     * 创建图表关联表
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(chartAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        // 数据校验
        chartService.validChart(chart, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除图表关联表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = chartService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图表关联表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ChartVO> getChartVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Chart chart = chartService.getById(id);
        ThrowUtils.throwIf(chart == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(chartService.getChartVO(chart, request));
    }

    /**
     * 分页获取图表关联表列表（仅管理员可用）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 查询数据库
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取图表关联表列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ChartVO>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                               HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        // 获取封装类
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }

    /**
     * 分页获取当前登录用户创建的图表关联表列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ChartVO>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(chartQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        // 获取封装类
        return ResultUtils.success(chartService.getChartVOPage(chartPage, request));
    }


    /**
     * 生成结果 By AI
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/genChartByAi")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                             GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        Chart chart = new Chart();
        BeanUtils.copyProperties(genChartByAiRequest, chart);
        chartService.validChart(chart, true);
        // excel 解析文件
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        // 生成用户输入内容
        String userMessage = genUserMessage(goal,csvData,chartType);
        String aiResult = aiManager.aiResponse(userMessage);
        BiResponse biResponse = getBiResponse(aiResult);
        return ResultUtils.success(biResponse);
    }



    private String genUserMessage(String goal,String chartType,String chartData){
        StringBuilder str = new StringBuilder();
        str.append("分析需求：").append("\n").append(goal).append("\n");
        if(!StringUtils.isBlank(chartType)){
            str.append("图表类型：").append("\n").append(chartType).append("\n");
        }
        str.append("原始数据:").append("\n");
        str.append(chartData);
        return str.toString();
    }

    private BiResponse getBiResponse(String aiResult){
        String[] res = aiResult.split("【【【【【" + "\n");
        if(res.length < 3){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"ai生成错误，请重试");
        }
        BiResponse biResponse = new BiResponse();
        biResponse.setEchartsData(res[1]);
        biResponse.setAnalysisResult(res[2]);
        return biResponse;
    }

    // endregion
}
